# -*- coding: utf-8 -*-

from TimeManager import TimeManager
from FileManager import FileManager
from TerminalManager import TerminalFactory
from flutereceiver import FluteReceiver
from VideoCommunicator import VideoCommunicator

from twisted.internet import reactor, threads

from os import path, sep
from signal import signal, SIGINT
import logging

# Files Constants
ROOT_DIR = path.abspath(path.dirname(__file__))
PARENT_DIR = sep.join(ROOT_DIR.split(sep)[:-1])
ZIP_DIR = path.join(PARENT_DIR, 'testfiles')
WIDGETS_DIR_REL = path.join(ROOT_DIR, 'unzipfiles')

# Server Constants
SERVER_PORT = 7000

class HomeboxApp:
    def __init__(self):
        # Init log
        self.log = logging.getLogger("AlicanteHomebox")
        logging.basicConfig()
        self.log.setLevel(logging.DEBUG)
        self.log.info("Starting homebox")    

        self.channelsList = {} # Each channel contains its interactif services and the terninals that are watching it
        self.filemanager = FileManager()
        self.timemanager = TimeManager(self.channelsList)
        self.flute = FluteReceiver(self.filemanager, self.timemanager)
        self.videoCommunicator = VideoCommunicator()
        
        reactor.listenTCP(SERVER_PORT, TerminalFactory(self.channelsList, self.videoCommunicator) )    
        signal(SIGINT, self.signal_handler)
        
    def signal_handler(self, signal, frame): 
        try:
            self.flute.killClients()
            reactor.stop()
        except:
            pass
        return 0
        
    def run(self):
        self.log.debug('Run server')

        reactor.callInThread(self.flute.reactorTest, "downloaded_zip/mapping.xml")
        #reactor.callInThread(self.flute.reactorTest, "downloaded_zip/survey.zip")
        #reactor.callInThread(self.flute.reactorTest, "downloaded_zip/survey2.zip")
        reactor.callInThread(self.timemanager.runTimer) 
        reactor.run()
       
if __name__ == '__main__':
    HomeboxApp().run()
  